package com.ruoyi.projects.apis;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.IgnoreAuth;
import com.ruoyi.common.annotation.LoginUserInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.BuConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.ApiBaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.projects.Vos.SlProductVo;
import com.ruoyi.projects.Vos.WxUserInfoDTO;
import com.ruoyi.projects.domain.*;
import com.ruoyi.projects.service.*;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 项目基础功能接口
 * @author yangz
 */
@RestController
@RequestMapping("/api/apiBase")
public class BaseApis extends ApiBaseController {

    private static final Logger log = LoggerFactory.getLogger(BaseApis.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IImgService imgService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private ISlActivitysService slActivitysService;

    @Autowired
    private ISlDemosService slDemosService;

    @Autowired
    private ISlQuestionsService slQuestionsService;

    @Autowired
    private ISlSysConfigService slSysConfigService;

    @Autowired
    private ISlProductService slProductService;

    /**
     * 系统配置信息查询
     */
    @PostMapping("/slSysConfig")
    @IgnoreAuth
    public ApiResult slSysConfig()
    {
        Object cacheObject = redisCache.getCacheObject(BuConstants.REDIS_SLSYSCONFIG_KEY);
        if (cacheObject==null){
            List<SlSysConfig> slSysConfigs = slSysConfigService.selectSysConfigList(new SlSysConfig());
            if (slSysConfigs.size()>0){
                SlSysConfig slSysConfig = slSysConfigs.get(0);
                if (StringUtils.isNotEmpty(slSysConfig.getSwiperIndex())){
                    slSysConfig.setSwiperIndexList(new ArrayList<String>(Arrays.asList(slSysConfig.getSwiperIndex().split(","))));
                }
                if (StringUtils.isNotEmpty(slSysConfig.getSwiperService())){
                    slSysConfig.setSwiperServiceList(new ArrayList<String>(Arrays.asList(slSysConfig.getSwiperService().split(","))));
                }
                redisCache.setCacheObject(BuConstants.REDIS_SLSYSCONFIG_KEY,slSysConfigs.get(0));
            }
            return ApiResult.success(slSysConfigs.get(0));
        }else {
            SlSysConfig cacheObject1 = (SlSysConfig) cacheObject;
            return ApiResult.success(cacheObject1);
        }
    }

    /**
     * 首页初始化接口
     *
     * @param dto
     * @return
     */
    @PostMapping("/initIndex")
    public ApiResult initIndex(@LoginUserInfo WxUserInfoDTO dto) {
        try {
            Map<String,Object> resultMap=new HashMap<>();
            //返回推荐产品
            SlProductVo vo =new SlProductVo();
            vo.setIfTop(BuConstants.ProductTop_YES);
            List<SlProductVo> slProducts = slProductService.queryAllProducts(vo);
            resultMap.put("slProducts",slProducts);
            if (dto == null) {
                //未登录
                resultMap.put("latestNoticeId",null);
                resultMap.put("latestActivityId",null);
            } else {
                //已登录，返回消息未读个数
                SysNotice sysNotice = noticeService.selectNewNotices();
                if (sysNotice!=null){
                    resultMap.put("latestNoticeId",sysNotice.getNoticeId());
                }else {
                    resultMap.put("latestNoticeId",null);
                }
                SlActivitys slActivitys=slActivitysService.selectNewActivity();
                if (slActivitys!=null){
                    resultMap.put("latestActivityId",slActivitys.getId());
                }else {
                    resultMap.put("latestActivityId",null);
                }
            }
            return ApiResult.success(resultMap);
        } catch (Exception e) {
            return ApiResult.error("保存用户信息失败");
        }
    }


    /**
     * 成功案例分页查询展示接口
     */
    @PostMapping("/slDemoList")
    @IgnoreAuth
    public TableDataInfo slDemoList(SlDemos vo)
    {
        Integer pageNum = vo.getPageNum();
        Integer pageSize = vo.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            PageHelper.startPage(pageNum, pageSize);
        }else {
            startPage();
        }
        List<SlDemos> slDemosList = slDemosService.selectSlDemosList(vo);
        return getDataTable(slDemosList);
    }

    /**
     * 智能问题分页查询展示接口
     */
    @PostMapping("/queryQuestionList")
    @IgnoreAuth
    public ApiResult queryQuestionList(SlQuestions vo)
    {
        vo.setIfFlag(BuConstants.FLAG_YES);
        List<SlQuestions> slQuestions = slQuestionsService.selectSlQuestionsList(vo);
        return ApiResult.success(slQuestions);
    }

    /**
     * 系统通知查询接口
     */
    @PostMapping("/sysNoticeList")
    @IgnoreAuth
    public TableDataInfo sysNoticeList(SysNotice vo)
    {
        Integer pageNum = vo.getPageNum();
        Integer pageSize = vo.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            PageHelper.startPage(pageNum, pageSize);
        }else {
            startPage();
        }
        List<SysNotice> sysNotices = noticeService.selectNoticeList(vo);
        TableDataInfo rspData = new TableDataInfo();
        SysNotice sysNotice = noticeService.selectNewNotices();
        if (sysNotice!=null){
            rspData.setLastId(sysNotice.getNoticeId());
        }else {
            rspData.setLastId(null);
        }
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(sysNotices);
        rspData.setTotal(new PageInfo(sysNotices).getTotal());
        return rspData;
    }

    /**
     * 系统通知查询接口
     */
    @PostMapping("/noticeDetail")
    @IgnoreAuth
    public ApiResult noticeDetail(@RequestBody SysNotice vo)
    {
        SysNotice sysNotice = noticeService.selectNoticeById(vo.getNoticeId());
        return ApiResult.success(sysNotice);
    }


    /**************************************************************************************************8888/

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/uploadAva")
    @IgnoreAuth
    public ApiResult uploadAva(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String originalFilename = file.getOriginalFilename();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Img img =new Img(originalFilename,url);
            int i = imgService.insertImg(img);
            if (i>0){
                ApiResult ajax = ApiResult.success();
                ajax.setData(img.getId());
                return ajax;
            }else {
                return ApiResult.error(ApiResult.EnumCode.ERROR);
            }
        }
        catch (Exception e)
        {
            return ApiResult.error(ApiResult.EnumCode.ERROR);
        }
    }

    /**
     * 上传微信头像专用接口
     * @param file
     * @return
     */
    @PostMapping("/uploadAvator")
    @IgnoreAuth
    public ApiResult uploadAvator(MultipartFile file) {
        try {
            log.info("开始处理头像上传请求");
            log.debug("上传的文件信息: name={}, size={}", file.getOriginalFilename(), file.getSize());

            if (file.isEmpty()) {
                log.warn("上传的文件为空");
                return ApiResult.error("上传文件不能为空");
            }

            String filePath = RuoYiConfig.getUploadPath();
            log.info("上传路径: {}", filePath);
            
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            log.info("上传成功，访问URL: {}", url);
            
            log.info("头像上传成功: {}", url);
            return ApiResult.success("上传成功", url);
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return ApiResult.error("头像上传失败：" + e.getMessage());
        }
    }

}
